﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    /*DEBUG VARS*/
    var DEBUG = false;

    function log(str) {
        
        if (DEBUG && console && console.log) {
            console.log(str);
        }
    }

    //Get strings out of resources
    var recentPostsTitle = WinJS.Resources.getString('recentPostsTitle').value;
    var categoryTitle = WinJS.Resources.getString('categoryTitle').value;
    var offlineTitle = WinJS.Resources.getString('offlineTitle').value;

    var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
    var currentOptions;

    var _appbar;
    var _post;
    var _images;
    var _element;
    var promise = null;

    var postLoaded = true;

    WinJS.UI.Pages.define("/pages/itemDetail/itemDetail.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            _element = element;
            currentOptions = options;

            element.querySelector('.pagetitle').innerHTML = options.item.title;

            //set progress ring
            var parent = element.querySelector('section');
            var pHeight = (parent.offsetHeight / 2) - parent.offsetTop;
            var ringContainer = element.querySelector('.progress-container');
            var rHeight = ringContainer.offsetHeight;
            var marginTop = pHeight + (rHeight / 2);
            ringContainer.style.marginTop = marginTop + "px";

            toggleLoading(true);

            //_post = options.item;
            _appbar = document.getElementById('appbar').winControl;

            //hide commands
            _appbar.hideCommands('cmdRemove', false);
            _appbar.hideCommands('cmdAdd', false);

            //share event listener
            dataTransferManager.addEventListener("datarequested", dataRequested);

            //check if it's a saved post
            if (options.item.key === offlineTitle) {
                _post = options.item;

                //Function to show iframes e.g. embed youtube
                MSApp.execUnsafeLocalFunction(function () {
                    toggleLoading(false);
                    if (_post !== null && typeof _post.content !== "undefined") {
                        document.getElementById('postContent').innerHTML = getDateAndAuthor(_post.date) + Helper.stripScripts(_post.content);
                        fireRemoveFunctions();
                    } else {
                        document.getElementById('postContent').innerHTML = "<h3>Im Moment besteht keine Internetverbindung.</h3>";
                    }

                });

                initAppBar();

                var main = element.querySelector("#postContent");
                _images = main.querySelectorAll('img');
                for (var i = 0; i < _images.length; i++) {
                    _images[i].addEventListener("click", imageHandler, false);
                }
            } else {
                promise = Data.getPostByURL(options.item.url).then(function (p) {
                    
                    _post = p;

                    if (promise._state.name !== "canceled") {
                        toggleLoading(false);
                        //Function to show iframes e.g. embed youtube
                        MSApp.execUnsafeLocalFunction(function () {
                            if (_post !== null && typeof _post.content !== "undefined") {
                                document.getElementById('postContent').innerHTML = getDateAndAuthor(_post.date) + Helper.stripScripts(_post.content);
                                fireRemoveFunctions();
                             
                            } else {
                                document.getElementById('postContent').innerHTML = "<h3>Im Moment besteht keine Internetverbindung.</h3>";
                            }

                        });
                    }
                    if (p == null) {
                        postLoaded = false;
                    } else {
                        postLoaded = true;
                    }

                    initAppBar();

                    var main = element.querySelector("#postContent");
                    _images = main.querySelectorAll('img');
                    for (var i = 0; i < _images.length; i++) {
                        _images[i].addEventListener("click", imageHandler, false);
                    }
                });
            }


            //override the backbutton to set all iframes source to ''
            //otherwise the app will chrash when a video is played and the user will press the back button
            var backButton = element.querySelector(".win-backbutton");
            backButton.addEventListener('click', backButtonHandler, false);
        },

        unload: function () {
            if (promise != null) {
                promise.cancel();
            }
            if (typeof _images !== "undefined") {
                for (var i = 0; i < _images.length; i++) {
                    _images[i].removeEventListener("click", imageHandler, false);
                    _images[i] = null;
                }
            }
            // TODO: Respond to navigations away from this page.
            dataTransferManager.removeEventListener("datarequested", dataRequested);
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            // TODO: Respond to changes in viewState.
            

        },

        getAnimationElements: function () {
            return [[this.element.querySelector("header")], [this.element.querySelector("section")]];
        }


    });

    function readOnlineHandler() {
        var uri = new Windows.Foundation.Uri(currentOptions.item.url);
        Windows.System.Launcher.launchUriAsync(uri);
    }

    function removePost() {

        var listOfPostIds = [];
        listOfPostIds.push(_post.id);

        //delete post by id
        Data.deletePosts(listOfPostIds).then(function (parameters) {
            console.log("test");
        });

        _appbar.hide();
        var btn = document.getElementById("cmdRemove");
        btn.removeEventListener('click', removePost, false);
        _appbar.hideCommands('cmdRemove', false);

        _appbar.showCommands('cmdAdd', true);
        document.getElementById("cmdAdd").addEventListener("click", addPost, false);
    }

    function addPost() {

        log("Add button recentPost pressed");
        var listOfPosts = [];
        listOfPosts.push(_post);

        //save array of selected posts in offline list 
        Data.saveToOfflineList(listOfPosts);

        //hide appbar
        _appbar.hide();
        var btn = document.getElementById("cmdAdd");
        btn.removeEventListener('click', addPost, false);
        _appbar.hideCommands('cmdAdd', false);

        _appbar.showCommands('cmdRemove', true);
        document.getElementById("cmdRemove").addEventListener("click", removePost, false);
    }

    function initAppBar() {

        //open in Browser Handler
        document.getElementById("readOnline").addEventListener("click", readOnlineHandler, false);

        promise = Data.checkIfSaved(currentOptions.item).then(function (parameters) {
            if (parameters === true) {
                _appbar.showCommands('cmdRemove', true);
                if (typeof document.getElementById("cmdRemove") !== "undefined") {
                    document.getElementById("cmdRemove").addEventListener("click", removePost, false);
                }

            } else {
                if (postLoaded) {
                    _appbar.showCommands('cmdAdd', true);
                    document.getElementById("cmdAdd").addEventListener("click", addPost, false);
                }
            }
        });
    }

    function imageHandler(event) {

        event.preventDefault();
        

    }

    function backButtonHandler(parameters) {
        if (promise != null) {
            promise.cancel();
        }
        var main = _element.querySelector("#postContent");
        var frames = main.querySelectorAll('iframe');

        for (var i = 0; i < frames.length; i++) {
            frames[i].setAttribute('src', '');
        }
    }

    function dataRequested(e) {
        var request = e.request;

        // Title is required

        var dataPackageTitle = Helper.htmlSpecialChars(currentOptions.item.title, true);
        //var dataPackageTitle = "Title";

        if ((typeof dataPackageTitle === "string") && (dataPackageTitle !== "")) {

            request.data.properties.title = dataPackageTitle;

            // The description is optional.
            var dataPackageDescription = Helper.htmlSpecialChars(currentOptions.item.excerpt, true);
            //var dataPackageDescription = "Description";

            //var dataPackageDescription = "";
            if ((typeof dataPackageDescription === "string") && (dataPackageDescription !== "")) {
                request.data.properties.description = dataPackageDescription;
            }

            try {
                request.data.setUri(new Windows.Foundation.Uri(currentOptions.item.url));
                //request.data.setUri(new Windows.Foundation.Uri("http://www.google.de"));


            } catch (e) {

            }

        } else {
            request.failWithDisplayText(SdkSample.missingTitleError);
        }
    }

    function getDateAndAuthor(date) {
        if (typeof date !== "undefined") {
            var fullDate = date.split(' ');
            var date = fullDate[0].split('-')[2];
            var month = fullDate[0].split('-')[1] - 1;
            var year = fullDate[0].split('-')[0];

            var time = fullDate[1].split(':');
            var minutes = time[1];
            var hours = time[0];

            var authorName = _post.author.name;

            var dateObject = new Date(year, month, date);
            var localDate = dateObject.toLocaleDateString();
            //date and author
            
            return "<h3 class='detailAuthorAndDate'>Veröffentlicht am " + localDate + " - " + hours + ":" + minutes + " von " + authorName + "</h3><br>";
        } else {
            return "";
        }
    }

    function removeElementById(id) {
        var element = document.getElementById(id);
        if (element !== null) {
            element.parentNode.removeChild(element);
        }
    }

    function removeElementByClass(c) {
        var elements = document.getElementsByClassName(c);
        for (var i = 0; i < elements.length; i++) {
            elements[i].parentNode.removeChild(elements[i]);
        }
    }

    function removeIframes(str) {
        var elements = document.getElementsByTagName('iframe');
        var saveForRemoval = [];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].src.indexOf(str) !== -1) {
                saveForRemoval.push(elements[i]);
            }
        }
        for (var j = 0; j < saveForRemoval.length; j++) {
            saveForRemoval[j].parentNode.removeChild(saveForRemoval[j]);
        }
    }

    function toggleLoading(isLoading) {
        if (isLoading) {
            _element.querySelector(".progress-container").style.display = "block";
        }
        else {
            _element.querySelector(".progress-container").style.display = "none";
        }
    }

    function fireRemoveFunctions() {
        console.log(">> itemDetail.js: fireRemoveFunctions() - add remove functions here <<");
        removeIframes();
    }

})();
